package cn.caplike.demo.rabbitmq.api.ack;

import cn.caplike.demo.rabbitmq.api.Application;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-19 12:18
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Application.RABBITMQ_HOST);
        connectionFactory.setPort(Application.RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();
        // 指定消息投递模式
        channel.confirmSelect();

        final String exchangeName = "test_ack_exchange";
        final String routingKey = "ack.save";

        // 发送消息
        for (int idx = 0; idx < 5; idx++) {
            final String msg = "Hello RabbitMQ Send ACK message!" + idx;
            Map<String, Object> map = new HashMap<>(1);
            map.put("idx", idx);

            Thread.sleep(2000);

            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)
                    .contentEncoding("UTF-8")
                    .headers(map).build();

            channel.basicPublish(exchangeName, routingKey, false, properties, msg.getBytes());
        }

        channel.addConfirmListener(
                (deliveryTag, multiple) -> System.out.println("HandleAck -> deliveryTag: " + deliveryTag + "; multiple: " + multiple),
                (deliveryTag, multiple) -> System.out.println("HandleNAck -> deliveryTag: " + deliveryTag + "; multiple: " + multiple)
        );
    }
}
